package com.sxt.filter;

import com.sxt.common.CodeMsg;
import com.sxt.common.Constant;
import com.sxt.common.Result;
import com.sxt.util.RespUtil;

import javax.servlet.*;
import javax.servlet.annotation.WebFilter;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;

/**
 *  登录拦截
 *      那些资源放行 :
 *          登录页面
 *          验证码
 *          处理登录的请求
 */
@WebFilter(value = {"*.do","*.jsp"})
public class LoginFilter implements Filter {
    @Override
    public void init(FilterConfig filterConfig) throws ServletException {

    }

    @Override
    public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException {
        HttpServletRequest req = (HttpServletRequest) request;
        HttpServletResponse resp = (HttpServletResponse) response;


        //获取session
        HttpSession session = req.getSession();
        //获取登录用户
        Object user = session.getAttribute(Constant.CURRENT_USER_KEY);
        //不为空 说明已经登录
        if (user != null){
            //放行
            chain.doFilter(req,resp);
            return;
        }
        //获取登录资源
        String uri = req.getRequestURI(); //获取请求的资源路径
        //登录页面放行 验证码放行
        if (uri.endsWith("index.jsp") || uri.endsWith("checkCode.do") || uri.endsWith("redirect.jsp") ){
            //放行
            chain.doFilter(req,resp);
            return;
        }
        //是否是处理登录的请求
        String service = req.getParameter("service");
        //处理登录的请求
        if (uri.endsWith("user.do") && "login".equals(service)){
            //放行
            chain.doFilter(req,resp);
            return;
        }
        //获取ajax请求标记
        //X-Requested-With: XMLHttpRequest
        String flag = req.getHeader("X-Requested-With");
        //一致说明ajax请求
        if ("XMLHttpRequest".equalsIgnoreCase(flag)){
            //JSON  告诉前端  需要 登录
            RespUtil.write(resp,new Result(CodeMsg.SYS_LOGIN_INVILD_ERROR));
            return;
        }
        //其他情况 不放行  去登录页面
        resp.sendRedirect("redirect.jsp");//302  parseData
    }

    @Override
    public void destroy() {

    }
}

